package cc.idoone.spring_boot_hello.amqp.sendconfirm;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author hemj
 * @since 2017/10/16
 */
@Component
public class CallbackSend implements RabbitTemplate.ConfirmCallback {

	private RabbitTemplate rabbitTemplate;

	@Autowired
	public CallbackSend(RabbitTemplate rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;
		rabbitTemplate.setConfirmCallback(this);
	}

	public void sendMsg(String content) {
		CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
		System.out.println("发送消息: " + correlationId);
		rabbitTemplate.convertAndSend(AmqpConfig.CB_EXCHANGE, AmqpConfig.CB_ROUTINGKEY, content, correlationId);
	}

	@Override
	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		System.out.println("回调ID: " + correlationData);
		if (ack) {
			System.out.println("消息发送成功");
		} else {
			System.out.println("消息发送失败:" + cause);
		}
	}
}
